package com.hcbd.tdwt.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.bd.BdToolFactory;
import com.hcbd.tdwt.util.StringUtil;
import com.cy.translucentparent.StatusNavUtils;
import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.ui.common.dialog.WarnDialog;
import com.hcbd.tdwt.ui.xingyu.dialog.LoadingDialog;
import com.hcbd.tdwt.ui.xingyu.dialog.OldProtocolDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import static android.content.Context.INPUT_METHOD_SERVICE;

abstract public class BaseFragment extends Fragment {
    protected Bundle savedInstanceState;
    private OldProtocolDialog oldProtocolDialog;
    protected Fragment currentFragment;
    protected boolean isRefreshing;
    private String TAG = getClass().getName();
    //申请权限请求码
    protected final int permissionRequestCode = 10;
    protected static final String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS};

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "onFragmentCreated: 打开 Fragment ");
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        if(BdToolFactory.app_type==BdToolFactory.XY_BG_TYPE||BdToolFactory.app_type==BdToolFactory.XY_PDA_BG_TYPE){
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            StatusNavUtils.setStatusNavBarColor(getActivity(), getActivity().getColor(R.color.deep_black), getActivity().getColor(R.color.white));
            setAndroidNativeLightStatusBar(false);
            getActivity().getWindow().setNavigationBarColor(getActivity().getColor(R.color.deep_black));
        }else {
            StatusNavUtils.setStatusBarColor(this.getActivity(),0x00000000);
        }
        this.savedInstanceState = savedInstanceState;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }
    //设置状态栏字体颜色
    public  void setAndroidNativeLightStatusBar(boolean dark) {
        View decor = getActivity().getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }
    protected abstract void init();

    /**
     * 隐藏软键盘
     */
    public void hideKeyboard() {
        InputMethodManager mInputMethodManager = (InputMethodManager)getActivity().getSystemService(INPUT_METHOD_SERVICE);
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                mInputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    /**

     * 隐藏软键盘

     */

    public  void hideSoftInput(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);

    }
    public void onSwitch(){

    }
    //加载弹框
    public LoadingDialog loadDialog;
    /**
     * 显示加载框
     */
    public void showLoading(String str) {
        if (loadDialog == null) {
            loadDialog = new LoadingDialog(this.getActivity(),str);
        }
        loadDialog.setTips(str);

        LoadingDialog.showDialog(loadDialog);
    }

    /**
     * 隐藏加载框
     */
    public void hideLoading() {
        if (loadDialog == null) return;
        LoadingDialog.shutDown(loadDialog);
    }
    public void toast(String tip){
        Toast.makeText(this.getActivity(),tip,Toast.LENGTH_SHORT).show();
    }

    public String getTextStr(EditText editText){
        return editText.getText().toString().trim();
    }
    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param serviceName
     *            是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public boolean isServiceWork(String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) this.getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }
    /**
     * 显示带取消的警告框
     */
    public void showOldProtocolDialog(String content,OldProtocolDialog.OnCloseListener onCloseListener) {
        if (oldProtocolDialog == null) {
            oldProtocolDialog = new OldProtocolDialog();
        }
        if (oldProtocolDialog.isAdded()) return;
        oldProtocolDialog.setData(this.getActivity(), content,onCloseListener);
        oldProtocolDialog.show(this.getActivity().getFragmentManager(), "");
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        hideInputKeyBord();
        EventBus.getDefault().unregister(this);
        Log.e(TAG, "onDestroyView: 关闭 Fragment ");
    }
    /**
     * 隐藏Activity所在Window的系统软键盘
     */
    public void hideInputKeyBord() {
        InputMethodManager inputMethodManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (null != inputMethodManager) {
            inputMethodManager.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0);
        }
    }
    /**
     * 检查权限
     */
    protected void openContacts() {
        //判断是否有权限
        if(ContextCompat.checkSelfPermission(MainApp.getInstance(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_CONTACTS},201);
        }else{
            Intent mailListIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            mailListIntent.addCategory("android.intent.category.DEFAULT");
            mailListIntent.setType("vnd.android.cursor.dir/phone_v2");
            startActivityForResult(mailListIntent, Constant.GET_MAIL_LIST_CONTACT_RESULT);
        }
    }
    @SuppressLint("Range")
    public String getPhoneNum(Intent data){
        ContentResolver reContentResolverol = getActivity().getContentResolver();
        Uri contactData = data.getData();
        Cursor phone = reContentResolverol.query(contactData,
                null,
                null,
                null,
                null);
        String number="";
        while (phone.moveToNext()) {
            String  userNumber  = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            number= StringUtil.formatPhoneNum(userNumber);
        }
        if (number.length() != 11) {
            toast("手机号码格式不对");
            return "";
        }
        return number;
    }
    /**
     * 显示警告框
     *
     * @param onClickListener
     */
    public void showWarnDialog(String str, View.OnClickListener onClickListener) {
        if (warnDialog == null) {
            warnDialog = new WarnDialog();
        }
        if (warnDialog.isAdded()) return;
        warnDialog.setData(getActivity(), str, onClickListener);
        warnDialog.show(getActivity().getFragmentManager(), "");
    }


    /**
     * 隐藏警告框
     */
    public void hideWarnDialog() {
        if (warnDialog != null) {
            warnDialog.dismiss();
        }
    }
    //警告框
    private WarnDialog warnDialog;
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }
    public void initMsgRegister(){
        EventBus.getDefault().register(this);
    }
    protected void switchFragment(Fragment targetFragment, int frameLayutId) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        if (!targetFragment.isAdded()) {
            if(currentFragment!=null){
                transaction.hide(currentFragment).add(frameLayutId, targetFragment).commit();
            }else{
                transaction.add(frameLayutId, targetFragment).commit();
            }
        } else {
            transaction.hide(currentFragment).show(targetFragment).commit();
        }
        currentFragment = targetFragment;
    }
}
